package com.bigtotoro.shuiyincamera.video;

import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.Main2Activity;
import com.bigtotoro.shuiyincamera.MusicCropActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

//视频背景音乐

public class VideoMusicActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "video-music";
    private View layout01;
    private VideoView videoView;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;
    private String path = "/storage/emulated/0/dakashuiyin/video/slice/1553506380742.mp4"; // 3s
    private String out;
    private float scale;
    private float videoX, videoY;
    private ProgressDialog mProgressDialog;

    private SeekBar alphaSeekBar, alphaSeekBar2;
    private TextView alphaToolTip, alphaToolTip2;

    private MediaPlayer mMediaPlayer;
    private View btn_add_music;
    private View layout02;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_music);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoMusicActivity.this,"video_music","编辑背景音乐");
        initBase();

        initView();


        path = getIntent().getStringExtra("path");
        findViewById(R.id.btn_save).setOnClickListener(this);

        VideoUtil.checkVideoDir();
        layout01 = findViewById(R.id.layout01);
        videoView = findViewById(R.id.video);

        videoView.setVideoURI(Uri.parse(path));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                videoWidth = mediaPlayer.getVideoWidth();
                videoHeight = mediaPlayer.getVideoHeight();
                videoDuration = mediaPlayer.getDuration();
                Log.d("main", "setOnPreparedListener duration " + videoDuration);

                videoView.start();
                mediaPlayer.setLooping(true); //循环播放
                mMediaPlayer = mediaPlayer;
                float voice = MyUtils.toFloat(mAalpha, 100);
                if (mMediaPlayer != null) {
                    mMediaPlayer.setVolume(voice, voice); //控制音量1F最大0F静音
                }


//                mediaPlayer.setVolume(0.2F,0.2F); //控制音量1F最大0F静音

                frameWidth = layout01.getWidth();
                frameHeight = layout01.getHeight();
                Log.d(TAG, "frame" + frameWidth + ":" + frameHeight);
                Log.d(TAG, "video" + videoWidth + ":" + videoHeight);
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

                //Get VideoView's current width and height
                int videoViewWidth = videoView.getWidth();
                int videoViewHeight = videoView.getHeight();

                float xScale = (float) videoViewWidth / videoWidth;
                float yScale = (float) videoViewHeight / videoHeight;

                //For Center Crop use the Math.max to calculate the scale
                //float scale = Math.max(xScale, yScale);
                //For Center Inside use the Math.min scale.
                //I prefer Center Inside so I am using Math.min
                scale = Math.min(xScale, yScale);

                float scaledWidth = scale * videoWidth;
                float scaledHeight = scale * videoHeight;

                //Set the new size for the VideoView based on the dimensions of the video
                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = (int) scaledWidth;
                layoutParams.height = (int) scaledHeight;
                videoView.setLayoutParams(layoutParams);

                videoView.invalidate();
                videoX = (frameWidth - layoutParams.width) / 2;
                videoY = (frameHeight - layoutParams.height) / 2;

                Log.d(TAG, "scaledWidth " + scaledWidth + " scaledHeight " + scaledHeight);
                Log.d(TAG, "video after set params");
                Log.d(TAG, "videoView" + videoView.getWidth() + ":" + videoView.getHeight());
                Log.d(TAG, "videoView getx " + videoView.getX() + " and getY " + videoView.getY());
            }
        });
    }

    private int mAalpha = 50;
    private int mAalpha2 = 50;

    private int isChanged1 = 0;
    private int isChanged2 = 0;

    private void initView() {
        layout02 = findViewById(R.id.layout02); //第二个拖动条先不显示
        layout02.setVisibility(View.INVISIBLE);
        btn_add_music = findViewById(R.id.btn_add_music);
        btn_add_music.setOnClickListener(this);
        alphaSeekBar = (SeekBar) findViewById(R.id.opacitySeekBar);
        alphaSeekBar2 = (SeekBar) findViewById(R.id.opacitySeekBar2);
        alphaToolTip = findViewById(R.id.opacityToolTip);
        alphaToolTip2 = findViewById(R.id.opacityToolTip2);
        alphaSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {  //视频背景音音量
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                isChanged1 = 1;
                mAalpha = progress;
                Log.i("音量", "mAalpha ====" + mAalpha + "  progress===" + progress);
                float voice = MyUtils.toFloat(mAalpha, 100);
                alphaToolTip.setText("  " + mAalpha + "%");
                if (mMediaPlayer != null) {
                    mMediaPlayer.setVolume(voice, voice); //控制音量1F最大0F静音
                }
//                if (progress < 10) {
//                    Log.i("音量", "progress<10 ====" + progress + "  voice===" + voice);
//                    alphaToolTip.setText("  " + mAalpha + "%");
//                    if (mMediaPlayer != null) {
//                        mMediaPlayer.setVolume(voice, voice); //控制音量1F最大0F静音
//                    }
//                } else if (progress < 200) {
//                    Log.i("音量", "progress<200 ====" + progress + "  voice===" + voice);
//                    alphaToolTip.setText(" " + mAalpha + "%");
//                    if (mMediaPlayer != null) {
//                        mMediaPlayer.setVolume(voice, voice); //控制音量1F最大0F静音
//                    }
//                } else {
//                    Log.i("音量", "progress其他====" + progress + "  voice===" + voice);
//                    alphaToolTip.setText(mAalpha + "" + "%");
//                    if (mMediaPlayer != null) {
//                        mMediaPlayer.setVolume(voice, voice); //控制音量1F最大0F静音
//                    }
//                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        alphaSeekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                isChanged2 = 1;
                mAalpha2 = progress;
                if (progress < 10)
                    alphaToolTip2.setText("  " + mAalpha2 + "%");
                else if (progress < 200)
                    alphaToolTip2.setText(" " + mAalpha2 + "%");
                else
                    alphaToolTip2.setText(mAalpha2 + "" + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        if (isChanged1 == 0) {
            alphaSeekBar.setProgress(mAalpha); //设置滚动条默认值
        }
        if (isChanged2 == 0) {
            alphaSeekBar2.setProgress(mAalpha2); //设置滚动条默认值
        }


    }

    private static final int REQUEST_CODE_ADD_MUSIC = 9003;
    private String musicPath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADD_MUSIC) {
                Log.i("视频处理", "onActivityResult 视频加水印");
                List<LocalMedia> selectList3 = PictureSelector.obtainMultipleResult(data);
                if (selectList3.size() > 0) {
                    musicPath = selectList3.get(0).getPath();
                    MyUtils.checkOrcopyFile(musicPath, new MyUtils.StrCallback() {
                        @Override
                        public void callback(String str, int isNew) {
                            if (str!=null && str.length()>0){
                                musicPath = str;
                            }
                        }
                    });

                    Log.i("视频处理", "现在的musicPath====" + musicPath);
                    layout02.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add_music:
                PictureSelector.create(this).openGallery(PictureMimeType.ofAudio())
                        .previewVideo(true).selectionMode(PictureConfig.SINGLE).videoMinSecond(1).forResult(REQUEST_CODE_ADD_MUSIC);
                break;
            case R.id.btn_save:
                if (musicPath!=null && musicPath.lastIndexOf(".")>0){
                    float voice1 = MyUtils.toFloat(mAalpha, 100);
                    float voice2 = MyUtils.toFloat(mAalpha2, 100);
                    Log.i("视频处理", "保存时musicPath====" + musicPath);

                    //添加友盟事件统计
                    MyUtils.addUmengEvent(VideoMusicActivity.this,"video_music_save","编辑背景音乐保存");

                    saveMusic(path, voice1, musicPath, voice2);

                }else {
                    Toast.makeText(this, "请选择要添加的背景音乐", Toast.LENGTH_SHORT).show();

                }
               
                break;
        }
    }

    /**
     * @param v  视频地址
     * @param vV 视频音量 0~2.0
     * @param m  音乐地址
     * @param mV 音乐音量 0~2.0
     */
    private void saveMusic(String v, float vV, String m, float mV) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("正在处理");
        mProgressDialog.show();

        out = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp4";
        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex [0:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,volume=%s[a0];[1:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,volume=%s[a1];[a0][a1]amix=inputs=2:duration=first[aout] -map [aout] -ac 2 -c:v copy -map 0:v:0 -preset superfast %s", v, m, vV, mV, out);
        Log.d(TAG, "cmd");
        Log.d(TAG, cmd);
        String[] commands = cmd.split(" ");
        try {
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i(TAG, "EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i(TAG, "EpEditor.execCmd onProgress " + progress);
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onCancel() {
                    Log.i(TAG, "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i(TAG, "EpEditor.execCmd onFailure");
                    Log.i(TAG, message);
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    private static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i(TAG, "去水印完成，跳转");
                Toast.makeText(VideoMusicActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setHeight(videoHeight);
                art.setWidth(videoWidth);
                art.setCreate_time(System.currentTimeMillis() + "");
                art.setPath(out);
                art.setType(1);
                art.save();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
//                FileUtil.ablumUpdate(VideoMusicActivity.this, art.getPath(),1);//更新相册
                Intent intent = new Intent(VideoMusicActivity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, out);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", videoWidth);
                intent.putExtra("height", videoHeight);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(VideoMusicActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            } else if (msg.what == MSG_CANCLE) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoMusicActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoMusicActivity");//统计页面
        MobclickAgent.onPause(this);
    }

}
